from flask import abort
from flask import g
from flask import redirect
from info.utils.common import login_user_data
from . import profile_bp
from flask import request, current_app, jsonify, session, render_template
from info import db
from info import constants
from info.utils.response_code import RET
from info.utils.image_store import qiniu_image_store
from info.models import Category, News, User


@profile_bp.route('/other_news_list')
def other_news_list():
    """展示新闻列表的"""
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_bp.route('/other_info')
@login_user_data
def other_info():
    """查看其他用户信息"""
    user = g.user

    # 获取其他用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    data = {
        "user_info": user.to_dict() if user else [],
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@profile_bp.route('/user_follow')
@login_user_data
def user_follow():
    """用户关注列表展示"""

    # 1.获取参数
    p = request.args.get("p", 1)
    # 获取用户对象
    user = g.user
    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    users = []
    current_page = 1
    total_page = 1
    if user:
        # 3.逻辑处理
        paginate = None
        try:
            # 用户设置dynamic当你只做查询的时候user.followed就是一个查询对象
            paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        except Exception as e:
            current_app.logger.error(e)
        # 模型列表
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    user_dict_list = []
    for user in users if users else []:
        user_dict_list.append(user.to_dict())

    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_follow.html", data=data)

@profile_bp.route('/news_list')
@login_user_data
def news_list():
    """用户新闻列表数据"""
    # 获取页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    paginate = None

    # 3.逻辑处理
    # user.collection_news由于指明了lazy="dynamic"在没有真正使用其数据的时候还是一个查询对象
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)

    # 模型列表
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_list = []
    for news in items if items else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        'news_list':news_dict_list,
        'current_page':current_page,
        'total_page':total_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_bp.route('/news_release', methods=["GET", "POST"])
@login_user_data
def news_release():
    """用户发布新闻"""
    user = g.user
    categories = None
    if request.method == 'GET':
        # 查询分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        # 模型列表转换成字典列表
        category_dict_list = []
        for category in categories if categories else []:
            category_dict_list.append(category.to_dict())

        # 移除最新分类(0)
        category_dict_list.pop(0)
        return render_template("news/user_news_release.html", data={"categories": category_dict_list})

    # POST请求发布新闻
    # 1.获取参数
    title = request.form.get("title")
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = '个人发布'
    # 2.校验参数
    # 2.1 判断否为空
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 3.逻辑处理
    # 保存图片
    image_data = index_image.read()
    try:
        image_name = qiniu_image_store(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传新闻图片到七牛云失败")

    news = News()
    news.title = title
    news.digest = digest
    news.category_id = category_id
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.source = source
    news.user_id = user.id
    # 新闻处于审核中
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="新闻保存到数据库异常")

        # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="发布新闻成功")


@profile_bp.route('/collection')
@login_user_data
def user_collection():
    """用户个人收藏"""

    # 获取页数
    p = request.args.get('p', 1)
    user = g.user

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    paginate = None
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
    # 那出来的是一个个列表  [<News 21>, <News 149>]
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_list = []
    for news in items if items else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "collections": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值处理

    return render_template("news/user_collection.html", data=data)


@profile_bp.route('/pass_info', methods=["GET", "POST"])
@login_user_data
def pass_info():
    """修改密码"""
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html', data={"user_info": user.to_dict()})

    params = request.json
    old_password = params.get("old_password")
    new_password = params.get("new_password")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    # 判断当前用户输入的老密码是不是正确的
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg="旧密码填写错误")
    # 修改密码
    user.password = new_password
    # 提交修改的密码
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="修改密码到数据库异常")
        # 4.组织返回值
    return jsonify(errno=RET.OK, errmsg="修改密码成功")


@profile_bp.route('/pic_info', methods=["GET", "POST"])
@login_user_data
def pic_info():
    """个人头像"""

    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})

    # 1.获取上传的文件
    avatar_data = request.files.get("avatar").read()

    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="请上传用户头像")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 3.逻辑处理
    try:
        image_name = qiniu_image_store(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传图片失败")
    # 保存图片名称到user对象的avatar_url中
    # 保存图片名称到user对象的avatar_url属性中
    user.avatar_url = image_name  # url域名 + image_name (方便后期更改域名)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存图片数据异常")
    # 4.返回值处理
    full_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        "avatar_url": full_url,
        "user_info": user.to_dict() if user else None,
    }


    return jsonify(errno=RET.OK, errmsg="修改用户头像成功", data=data)



@profile_bp.route('/base_info', methods=["GET", "POST"])
@login_user_data
def base_user_info():
    """个人基本信息"""

    # 1.获取用户数据
    user = g.user
    if request.method == 'GET':
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_base_info.html", data=data)

    params = request.json
    nick_name = params.get('nick_name')
    signature = params.get('signature')
    gender = params.get('gender')

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="提交参数不足")
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="性别数据错误")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 3.逻辑处理
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    session['nick_name'] = nick_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改用户数据异常")

        # 4.返回值处理

    return jsonify(errno=RET.OK, errmsg="修改用户数据成功")


# 127.0.0.1:5000/news/info
@profile_bp.route('/info')
@login_user_data
def user_info():
    """这是一个个人主页"""

    # 1.获取用户数据
    user = g.user

    if not user:
        return redirect('/')

    return render_template('news/user.html', data={"user_info": user.to_dict() if user else None})









